﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Models.V2;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 商品接口
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/Product")]
    [Authorize]
    [ApiController]
    public class ProductController : BaseController
    {
        private readonly IIcApiService _icApiService;
        private readonly IStoreApiService _storeApiService;
        private readonly ICacheService _cacheService;
        private readonly IStoreService _storeService;
        private readonly IMediator _mediator;
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.V2.ProductController"/> class.
        /// </summary>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="storeApiService">Store API service.</param>
        /// <param name="cacheService">cacheService</param>
        /// <param name="storeService"></param>
        /// <param name="mediator"></param>
        public ProductController(IIcApiService iicApiService, IStoreApiService storeApiService, ICacheService cacheService, IStoreService storeService, IMediator mediator)
        {
            _icApiService = iicApiService;
            _storeApiService = storeApiService;
            _cacheService = cacheService;
            _storeService = storeService;
            _mediator = mediator;
        }



        /// <summary>
        /// GetIndexGoodsList
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"storeid":"1"}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetIndexGoodsList([FromBody]GetIndexGoodsListReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Storeid == 0) {
                return Ok(new Domain.Response.BaseResult<string>("", 999, "出错了，请升级App"));
            }
            var ckey = Constant.INDEXGOODSLIST + data.Storeid;
            var entity = await _cacheService.GetAsync<List<IndexGoods>>(ckey).ConfigureAwait(false);
            if (entity == null) {
                entity = await _storeApiService.GetIndexGoodsList(data.Storeid).ConfigureAwait(false);
                if (entity != null) {
                    await _cacheService.AddAsync(ckey, entity, TimeSpan.FromMinutes(10), true).ConfigureAwait(false);
                }
            }
            return Ok(new { code = 0, content = entity });
        }
        /// <summary>
        /// Gets the stock product.
        /// </summary>
        /// <returns>The stock product.</returns>
        /// <param name="data">Data.</param>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetStockProduct([FromBody]GetProductReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Storeid == 0) {
                return Ok(new { code = 999, msg = "storeid 有误" });
            }
            if (data.Productid == 0) {
                return Ok(new { code = 999, msg = "productid 有误" });
            }
            var storeinfo = await _storeService.GetDetail<ICasaMielSession>(data.Storeid).ConfigureAwait(false);
            if (storeinfo == null) {
                return Ok(new { code = 999, msg = "storeid 有误" });
            }

            var entity = await _storeApiService.GetGoodsById(data.Storeid.ToString(CultureInfo.CurrentCulture), data.Productid.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);

          
            var apimode = new { code = 0, content = entity };
            return new JsonResult(apimode);
        }
        /// <summary>
        /// 商品信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"storeid":"1","productid":"1"}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetProduct([FromBody]GetProductReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Storeid == 0) {
                return Ok(new { code = 999, msg = "storeid 有误" });
            }
            if (data.Productid == 0) {
                return Ok(new { code = 999, msg = "productid 有误" });
            }
            var storeinfo = await _storeService.GetDetail<ICasaMielSession>(data.Storeid).ConfigureAwait(false);
            if (storeinfo == null) {
                return Ok(new { code = 999, msg = "storeid 有误" });
            }

            var entity = await _storeApiService.GetGoodsById(data.Storeid.ToString(CultureInfo.CurrentCulture), data.Productid.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);

            var dto = new IcPriceReq();

            if (entity != null) {
                dto.Product = new List<ProductItemReq>();
                foreach (var item in entity.GoodsList) {
                    dto.Product.Add(new ProductItemReq { Pid = item.RelationId.ToString(CultureInfo.CurrentCulture) });
                    // item.Status = 1;
                    //Console.WriteLine(item.RelationId.ToString());
                }

                dto.Shopid = entity.StoreRelationId;

                var zmodel = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                //var zmodel = await _icApiService.icprice(dto);
                //if (zmodel != null) {
                //    for (int i = 0; i < entity.GoodsList.Count; i++) {
                //        var t = zmodel.product.Find(a => a.pid == entity.GoodsList[i].RelationId.ToString(CultureInfo.CurrentCulture));
                //        if (t != null && t.icprice > 0) {
                //            entity.GoodsList[i].Price = $"{t.originprice}";
                //            entity.GoodsList[i].costPrice = $"{t.icprice}";
                //            if (storeinfo.IsLimitStock == 1) {
                //                entity.GoodsList[i].StockQuentity = 100;
                //            } else {
                //                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                //                    if (t.count > 0) {
                //                        int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(entity.GoodsList[i].RelationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)).ConfigureAwait(false);
                //                        entity.GoodsList[i].StockQuentity = t.count - a;
                //                    } else {
                //                        entity.GoodsList[i].StockQuentity = t.count;
                //                    }
                //                } else {
                //                    entity.GoodsList[i].StockQuentity = t.count;
                //                }

                //            }
                //            entity.GoodsList[i].Status = 0;
                //        }
                //    }
                //}
            }
            var apimode = new { code = 0, content = entity };
            return new JsonResult(apimode);
        }
        /// <summary>
        /// GetProductList
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>
        /// {"tagid":1,"pageindex":1,"pagesize":10}
        /// </remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetProductList([FromBody]GetProductListReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            //int TagId, int pageindex, int pagesize
            var result = await _storeApiService.GetGoodsList(data.Tagid, data.Pageindex, data.Pagesize).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            if (dynamicdata["ResultNo"].ToString() == "00000000") {
                var entity = JsonConvert.DeserializeObject<List<GoodsGetListRsp>>(dynamicdata["Data"].ToString());
                var pageindex = dynamicdata["PageIndex"].ToInt32(1);
                var pagesize = dynamicdata["PageSize"].ToInt32(10);
                var total = dynamicdata["Total"].ToInt32(0);
                var model = new { code = 0, pageindex = pageindex, pagesize = pagesize, total = total, content = entity };
                return Ok(model);
            }
            return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
        }

        /// <summary>
        /// Gets the stock product list.
        /// </summary>
        /// <returns>The stock product list.</returns>
        /// <param name="req">Req.</param>
        /// <remarks>{"storeId":1}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetStockProductList([FromBody]JObject req)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            var command = new GetProductStockListByStoreIdCommand(req["storeId"].ToInt32(0));
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return Ok(result);
        }
        /// <summary>
        /// 获取首页Tag.
        /// </summary>
        /// <returns>The index tag list.</returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetIndexTagList()
        {
            var list = await _storeApiService.GetIndexTagList().ConfigureAwait(false);
            var model = new { code = 0, Content = list };
            return Ok(model);
        }
        ///// <summary>
        ///// 商品类别
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("[Action]")]
        //public async Task<IActionResult> GetCategory()
        //{
        //    var model = new ApiModel { content = "[{\"catename\":\"蛋黄酥\"},{\"catename\":\"蛋黄酥\"}]" };
        //    return Ok(model);
        //}

        /// <summary>
        /// Products the add collect.
        /// </summary>
        /// <returns>The add collect.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// {"productBaseId":"1"}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<IActionResult> ProductAddCollect([FromBody] JObject data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            await _storeApiService.AddCollectAsync(data["productBaseId"].ToInt32(0), mobile).ConfigureAwait(false);
            return Ok(new { code = 0, Content = "" });
        }

        /// <summary>
        /// Cancles the product.
        /// </summary>
        /// <returns>The product.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"productBaseId":"1"}</remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<IActionResult> CancleProduct([FromBody] JObject data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            await _storeApiService.CancelCollectAsync(data["productBaseId"].ToInt32(0), mobile).ConfigureAwait(false);
            return Ok(new { code = 0, content = "" });
        }
        /// <summary>
        /// Products the check collect.
        /// </summary>
        /// <returns>The check collect.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"productBaseId":"1"}</remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<IActionResult> ProductCheckCollect([FromBody] JObject data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            bool a = await _storeApiService.ProductCheckCollect(data["productBaseId"].ToInt32(0), mobile).ConfigureAwait(false);
            return Ok(new { code = 0, content = new { collected = a } });
        }

        /// <summary>
        /// Products the clear collect.
        /// </summary>
        /// <returns>The clear collect.</returns>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<IActionResult> ProductClearCollect([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            await _storeApiService.ClearCollectAsync(mobile).ConfigureAwait(false);
            return Ok(new { code = 0, Content = "" });
        }
        /// <summary>
        /// Gets the collect list.
        /// </summary>
        /// <returns>The collect list.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// {"pageIndex":"1","pageSize":"10"}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<IActionResult> GetCollectList([FromBody] JObject data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var result = await _storeApiService.GetCollectListAsync(data["pageIndex"].ToInt32(1), data["pageSize"].ToInt32(10), mobile).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            var entity = JsonConvert.DeserializeObject<List<Application.Models.Store.GoodsCollectRsp>>(dynamicdata["Data"].ToString());
            var pageindex = dynamicdata["PageIndex"].ToInt32(1);
            var pagesize = dynamicdata["PageSize"].ToInt32(10);
            var total = dynamicdata["Total"].ToInt32(0);
            return Ok(new { code = 0, pageindex = pageindex, pagesize = pagesize, total = total, content = entity });

        }
    }
}